package com.mengdie.shuidi.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.event.CouponEvent;
import com.mengdie.shuidi.event.PayEvent;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.DiscountEntity;
import com.mengdie.shuidi.model.OrderEntity;
import com.mengdie.shuidi.model.PackageEntity;
import com.mengdie.shuidi.model.UserEnetity;
import com.mengdie.shuidi.ui.activity.ReplacePhoneActivity;
import com.mengdie.shuidi.ui.adapter.PackageAdapterV2;
import com.mengdie.shuidi.ui.discount.fragment.DiscountActivity;
import com.mengdie.shuidi.ui.interfaces.PayHelper;
import com.mengdie.shuidi.ui.interfaces.PayView;
import com.mengdie.shuidi.utils.ToastUtil;
import com.mengdie.shuidi.utils.core.EmptyUtils;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/11.
 */

public class PayFragmentV2 extends Fragment implements PayView {
    @Bind(R.id.rl_title_all)
    RelativeLayout mRlTitleAll;
    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.rv_pay_list)
    RecyclerView mRvPayList;
    @Bind(R.id.rl_go_bind_phone)
    RelativeLayout mRlGoBindPhone;
    @Bind(R.id.rl_package_wechat)
    RelativeLayout mRlPackageWechat;
    @Bind(R.id.rl_package_alipay)
    RelativeLayout mRlPackageAlipay;
    @Bind(R.id.iv_package_wechat)
    ImageView mIvPackageWechat;
    @Bind(R.id.iv_package_alipay)
    ImageView mIvPackageAlipay;
    @Bind(R.id.tv_package_discount)
    TextView mTvPackageDiscount;
    @Bind(R.id.tv_package_online)
    TextView mTvPackageOnline;
    @Bind(R.id.tv_package_money)
    TextView mTvPackageMoney;
    private View rootView;
    private List<PackageEntity> packageList = new ArrayList<>();
    private PackageAdapterV2 mPackageAdapter;

    private UserEnetity userInfo;
    private String mPayType = "2";
    private PackageEntity mPackage;
    private String mCoupon = "";
    private DiscountEntity mDiscount;
    private PayHelper mPayHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.activity_pay, container, false);
            ButterKnife.bind(this, rootView);
            EventBus.getDefault().register(this);
            getBarHeight();
            init();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        getUserInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void init() {
        mTvGenericTitle.setText("套餐购买");
        mTvPackageOnline.setText(MDUserMgr.getInstance().getNum());
        mPayHelper = new PayHelper(getActivity(), this);
        mRlGenericBack.setVisibility(View.GONE);
        mPackageAdapter = new PackageAdapterV2(packageList);
        mRvPayList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvPayList.setAdapter(mPackageAdapter);
        mRvPayList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                for (int i = 0; i < packageList.size(); i++) {
                    if (i == position) {
                        packageList.get(position).setCheck(true);
                    } else {
                        packageList.get(i).setCheck(false);
                    }
                }
                mPackage = packageList.get(position);
                mPackageAdapter.notifyDataSetChanged();
                updateMoney();
            }
        });
        getPackageList();
        setCheck(mPayType);
    }


    private void setCheck(String type) {
        mPayType = type;
        mRlPackageWechat.setSelected(type.equals("2") ? true : false);
        mRlPackageAlipay.setSelected(type.equals("1") ? true : false);
        mIvPackageWechat.setVisibility(type.equals("2") ? View.VISIBLE : View.GONE);
        mIvPackageAlipay.setVisibility(type.equals("1") ? View.VISIBLE : View.GONE);
    }


    private void getPackageList() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "buy/packages")
                .params("pak_origin", "4")
                .tag("pay")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type packageType = new TypeToken<BaseModel<List<PackageEntity>>>() {
                        }.getType();
                        BaseModel<List<PackageEntity>> packList;
                        try {
                            packList = gson.fromJson(s, packageType);
                        } catch (JsonSyntaxException e) {
                            packList = gson.fromJson(s, BaseModel.class);
                        }
                        if (packList.getRet().equals("0")) {
                            packageList = packList.getData();
                            packageList.get(0).setCheck(true);
                            mPackage = packageList.get(0);
                            updateMoney();
                            mPackageAdapter.setNewData(packageList);
                        } else {
                            ToastUtil.showToast(packList.getMsg());
                        }

                    }
                });
    }


    private void updateMoney() {
        if (EmptyUtils.isNotEmpty(mDiscount)) {
            mTvPackageDiscount.setText("￥" + mDiscount.getMoney());
            mTvPackageMoney.setText("￥" + (Integer.valueOf(mPackage.getShowPrice()) - Integer.valueOf(mDiscount.getMoney())));
        } else {
            mTvPackageMoney.setText("￥" + (Integer.valueOf(mPackage.getShowPrice()) * Integer.valueOf(MDUserMgr.getInstance().getNum())));
        }

    }


    /**
     * 获取用户信息
     */
    public void getUserInfo() {

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "account/get_user_all")
                .tag(getActivity())
                .upJson(mapSession())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Logger.e("用户信息:" + s);
                        Gson gson = new Gson();
                        Type userType = new TypeToken<BaseModel<UserEnetity>>() {
                        }.getType();
                        BaseModel<UserEnetity> baseModel;
                        try {
                            baseModel = gson.fromJson(s, userType);
                        } catch (JsonSyntaxException e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }
                        if (baseModel.getRet().equals("0")) {
                            userInfo = baseModel.getData();
                            if (EmptyUtils.isEmpty(baseModel.getData().getPhone())) {
                                mRlGoBindPhone.setVisibility(View.VISIBLE);
                            } else {
                                mRlGoBindPhone.setVisibility(View.GONE);
                            }
                        } else {
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });
    }

    private void getCounpon(final String coupon) {
        Map<String, String> map = new HashMap<>();
        map.put("coupon_num", coupon);
        JSONObject json = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "ucenter/coupon_info")
                .tag(getActivity())
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type counponType = new TypeToken<BaseModel<DiscountEntity>>() {
                        }.getType();
                        BaseModel<DiscountEntity> baseModel;
                        try {
                            baseModel = gson.fromJson(s, counponType);
                        } catch (JsonSyntaxException e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }
                        if (baseModel.getRet().equals("0")) {
                            mDiscount = baseModel.getData();
                            mCoupon = coupon;
                            updateMoney();
                        } else {
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });
    }

    @OnClick({R.id.rl_package_wechat, R.id.rl_package_alipay, R.id.rl_package_discount,
            R.id.tv_package_submit, R.id.rl_go_bind_phone, R.id.iv_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_package_wechat:
                setCheck("2");
                break;
            case R.id.rl_package_alipay:
                setCheck("1");
                break;
            case R.id.rl_package_discount:
                Intent discount = new Intent(getActivity(), DiscountActivity.class);
                getActivity().startActivity(discount);
                break;
            case R.id.tv_package_submit:
                getOrderId(mCoupon, mTvPackageMoney.getText().toString());
                break;
            case R.id.rl_go_bind_phone:
                Intent phone = new Intent(getActivity(), ReplacePhoneActivity.class);
                Bundle phoneb = new Bundle();
                phoneb.putString("phone", userInfo.getPhone());
                phoneb.putString("name", userInfo.getUsername());
                phone.putExtras(phoneb);
                startActivity(phone);
                break;
            case R.id.iv_del:
                mRlGoBindPhone.setVisibility(View.GONE);
                break;
        }
    }


    /**
     * 获取订单ID
     *
     * @param coupon
     * @param money
     */
    private void getOrderId(String coupon, String money) {
        Map<String, String> map = new HashMap<>();
        map.put("req_type", "2");
        map.put("balance_flag", "false");
        map.put("money", money.substring(1, money.length()));
        map.put("coupon", coupon);
        map.put("pak_id", mPackage.getId() + "");
        map.put("exec_type", "add_time");
        map.put("num", "1");
        map.put("terminal_type", "Android");
        map.put("add_terminal", "0");
        map.put("username", MDUserMgr.getInstance().getUsername());
        JSONObject json = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getPayUrl() + "core/bus/gateway")
                .upJson(json)
                .tag("order")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type oderType = new TypeToken<BaseModel<OrderEntity>>() {
                        }.getType();

                        BaseModel<OrderEntity> orderBase;
                        try {
                            orderBase = gson.fromJson(s, oderType);
                        } catch (JsonSyntaxException e) {
                            orderBase = gson.fromJson(s, BaseModel.class);
                        }
                        if (orderBase.getRet().equals("0")) {
                            setInfo();
                            mPayHelper.setOrder(orderBase.getData().getOrder(), mPayType);
                        } else {
                            ToastUtil.showToast(orderBase.getMsg());
                        }
                    }
                });

    }

    /**
     * 网络请求参数
     *
     * @return
     */
    private String mapSession() {
        HashMap<String, String> map = new HashMap<>();
        map.put("session_id", MDAccountMgr.getInstance().getSessionId());
        JSONObject json = new JSONObject(map);
        return json.toString();
    }


    /**
     * 获取状态栏高度——方法1
     */
    private void getBarHeight() {
        int statusBarHeight1 = -1;
//获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mRlTitleAll.getLayoutParams();
        layoutParams.setMargins(0, statusBarHeight1, 0, 0);
        mRlTitleAll.setLayoutParams(layoutParams);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CouponEvent event) {
        getCounpon(event.getCoupon());
    }

    @Override
    public void paySucc() {
    }

    @Override
    public void payFial() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PayEvent event) {
    }

    private void setInfo() {
        mCoupon = "";
        mDiscount = null;
        mTvPackageDiscount.setText("请选择");
        mTvPackageMoney.setText("￥" + (Integer.valueOf(mPackage.getShowPrice()) * Integer.valueOf(MDUserMgr.getInstance().getNum())));
    }

}
